# utils/security.py
import bcrypt


def hash_password(plain_password: str) -> str:
    """
    对明文密码进行 bcrypt 哈希（自动加盐）
    返回 base64 编码的字符串（便于 JSON 存储）
    """
    salt = bcrypt.gensalt()
    hashed = bcrypt.hashpw(plain_password.encode('utf-8'), salt)
    return hashed.decode('utf-8')  # 转为字符串


def verify_password(plain_password: str, hashed_password: str) -> bool:
    """
    验证明文密码是否与哈希匹配
    """
    try:
        return bcrypt.checkpw(
            plain_password.encode('utf-8'),
            hashed_password.encode('utf-8')
        )
    except Exception:
        return False